﻿using System.Diagnostics;
using System.IO;
using System.Windows.Interactivity;
using System.Windows.Media;
using DevExpress.Xpf.Bars;
using DevExpress.Xpf.Grid;
using DevExpress.XtraPrinting;

namespace Loki.UI.Wpf
{
    public class TreeListExcelExportBehaviour : Behavior<TreeListControl>
    {
        protected override void OnAttached()
        {
            base.OnAttached();
            TreeListView L_View = AssociatedObject.View as TreeListView;

            L_View.ShowGridMenu += L_View_ShowGridMenu;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            TreeListView L_View = AssociatedObject.View as TreeListView;
            L_View.ShowGridMenu -= L_View_ShowGridMenu;
        }

        private void L_Export_ItemClick(object sender, ItemClickEventArgs e)
        {
            TreeListView L_View = AssociatedObject.View as TreeListView;
            string L_FileName = Path.GetTempFileName() + ".xlsx";
            XlsxExportOptions L_Options = new XlsxExportOptions();
            L_Options.ExportMode = XlsxExportMode.SingleFilePageByPage;
            L_Options.TextExportMode = TextExportMode.Text;
            L_View.ExportToXlsx(L_FileName, L_Options);
            Process.Start(L_FileName);
        }

        private void L_View_ShowGridMenu(object sender, GridMenuEventArgs e)
        {
            BarItemLinkSeparator L_Separator = new BarItemLinkSeparator();

            BarButtonItem L_Export = new BarButtonItem();
            L_Export.Name = "Export";
            L_Export.Content = "Export menu";
            L_Export.Glyph = AssociatedObject.FindResource("MNI_excel") as ImageSource;
            L_Export.BarItemDisplayMode = BarItemDisplayMode.ContentAndGlyph;
            L_Export.ItemClick += L_Export_ItemClick;

            e.Customizations.Add(L_Separator);
            e.Customizations.Add(L_Export);
        }
    }
}